package itpenguin.review;

import itpenguin.common.PMFactory;
import itpenguin.review.entities.Item;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TopPageServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		PersistenceManager pm = PMFactory.getInstance().getPersistenceManager();
		Query query = pm.newQuery("select from itpenguin.review.entities.Item order by reviewDate desc range 0, 5"); 
		List<Item> reviewList = (List<Item>) query.execute();
		req.setAttribute("newReviews", pm.detachCopyAll(reviewList));
		
		// 最新更新日をセット
		resp.addDateHeader("Last-Modified", reviewList.get(0).getLastModified().getTime());
		
		query = pm.newQuery("select from itpenguin.review.entities.Item "
				+ "where reviewYear == yearParam "
				+ "parameters int yearParam, "
				+ "order by score desc range 0, 5");
		reviewList = (List<Item>) query.execute((short)0);
		req.setAttribute("ranking", pm.detachCopyAll(reviewList));
		
		pm.close();
		RequestDispatcher rd = req.getRequestDispatcher("/WEB-INF/template/main.jsp");
		rd.forward(req, resp);
	}
	
}
